package com.taxx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taxx.common.Result;
import com.taxx.dto.TaxPlatformReportDTO;
import com.taxx.entity.TaxPlatformReport;
import com.taxx.enums.ReportStatusEnums;
import com.taxx.service.TaxPlatformReportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

/**
 * 平台信息报送管理Controller
 */
@Slf4j
@RestController
@RequestMapping("/tax/platform")
public class TaxPlatformReportController {

    @Autowired
    private TaxPlatformReportService taxPlatformReportService;

    /**
     * 分页查询平台信息报送记录
     */
    @GetMapping("/list")
    public Result<Page<TaxPlatformReport>> getList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String batchCode,
            @RequestParam(required = false) String creditCode,
            @RequestParam(required = false) Integer reportStatus,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {

        try {
            Page<TaxPlatformReport> pageParam = new Page<>(page, size);
            QueryWrapper<TaxPlatformReport> queryWrapper = new QueryWrapper<>();

            // 添加调试日志
            log.info("查询参数: page={}, size={}, batchCode={}, creditCode={}, reportStatus={}, startDate={}, endDate={}",
                    page, size, batchCode, creditCode, reportStatus, startDate, endDate);

            // 添加查询条件
            if (batchCode != null && !batchCode.trim().isEmpty()) {
                queryWrapper.like("batch_code", batchCode.trim());
            }
            if (creditCode != null && !creditCode.trim().isEmpty()) {
                queryWrapper.like("credit_code", creditCode.trim());
                log.info("添加统一社会信用代码查询条件: {}", creditCode.trim());
            }
            if (reportStatus != null) {
                queryWrapper.eq("report_status", reportStatus);
                log.info("添加报送状态查询条件: {}", reportStatus);
            }
            if (startDate != null) {
                queryWrapper.ge("create_time", startDate);
                log.info("添加开始时间查询条件: {}", startDate);
            }
            if (endDate != null) {
                queryWrapper.le("create_time", endDate);
                log.info("添加结束时间查询条件: {}", endDate);
            }

            queryWrapper.orderByDesc("create_time");

            log.info("执行查询，查询条件: {}", queryWrapper.getCustomSqlSegment());

            Page<TaxPlatformReport> result = taxPlatformReportService.page(pageParam, queryWrapper);

            log.info("查询结果: total={}, records.size={}", result.getTotal(), result.getRecords().size());

            return Result.success(result);
        } catch (Exception e) {
            log.error("查询平台信息报送记录失败", e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取平台信息报送记录
     */
    @GetMapping("/{id}")
    public Result<TaxPlatformReport> getById(@PathVariable Long id) {
        try {
            TaxPlatformReport report = taxPlatformReportService.getById(id);
            if (report == null) {
                return Result.error("记录不存在");
            }
            return Result.success(report);
        } catch (Exception e) {
            log.error("获取平台信息报送记录失败", e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 创建平台信息报送记录
     */
    @PostMapping
    public Result<String> create(@Validated @RequestBody TaxPlatformReportDTO dto) {
        try {
            TaxPlatformReport report = new TaxPlatformReport();
            BeanUtils.copyProperties(dto, report);
            
            if (report.getReportStatus() == null) {
                report.setReportStatus(ReportStatusEnums.WAIT_SUBMIT.getCode()); // 待报送
            }
            
            boolean success = taxPlatformReportService.save(report);
            if (success) {
                return Result.success("创建成功");
            } else {
                return Result.error("创建失败");
            }
        } catch (Exception e) {
            log.error("创建平台信息报送记录失败", e);
            return Result.error("创建失败: " + e.getMessage());
        }
    }

    /**
     * 更新平台信息报送记录
     */
    @PutMapping("/{id}")
    public Result<String> update(@PathVariable Long id, @Validated @RequestBody TaxPlatformReportDTO dto) {
        try {
            TaxPlatformReport existingReport = taxPlatformReportService.getById(id);
            if (existingReport == null) {
                return Result.error("记录不存在");
            }
            
            // 检查是否已报送
            if (existingReport.getReportStatus() != null && existingReport.getReportStatus() > 0) {
                return Result.error("已报送的记录不能修改");
            }
            
            BeanUtils.copyProperties(dto, existingReport);
            existingReport.setId(id); // 确保ID不被覆盖
            
            boolean success = taxPlatformReportService.updateById(existingReport);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新平台信息报送记录失败", e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除平台信息报送记录
     */
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        try {
            TaxPlatformReport existingReport = taxPlatformReportService.getById(id);
            if (existingReport == null) {
                return Result.error("记录不存在");
            }
            
            // 检查是否已报送
            if (existingReport.getReportStatus() != null && existingReport.getReportStatus() > 0) {
                return Result.error("已报送的记录不能删除");
            }
            
            boolean success = taxPlatformReportService.removeById(id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除平台信息报送记录失败", e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除平台信息报送记录
     */
    @DeleteMapping("/batch")
    public Result<String> batchDelete(@RequestBody List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要删除的记录");
            }
            
            // 检查是否包含已报送的记录
            List<TaxPlatformReport> reports = taxPlatformReportService.listByIds(ids);
            for (TaxPlatformReport report : reports) {
                if (report.getReportStatus() != null && report.getReportStatus() > 0) {
                    return Result.error("包含已报送的记录，不能删除");
                }
            }
            
            boolean success = taxPlatformReportService.removeByIds(ids);
            if (success) {
                return Result.success("批量删除成功");
            } else {
                return Result.error("批量删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除平台信息报送记录失败", e);
            return Result.error("批量删除失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有平台信息报送记录（不分页）
     */
    @GetMapping("/all")
    public Result<List<TaxPlatformReport>> getAll() {
        try {
            List<TaxPlatformReport> list = taxPlatformReportService.list();
            return Result.success(list);
        } catch (Exception e) {
            log.error("获取所有平台信息报送记录失败", e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }
}
